#include "DInput.h"
#include "d3dUtil.h"
#include "d3dApp.h"
#include <commctrl.h>
#include <basetsd.h>

// Changes made by zach 01/28/08
BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE* pdidInstance, VOID* pContext);

IDirectInputDevice8		*mJoystick[2];


DIJOYSTATE2				js;

// Zach
DIJOYSTATE2				js2;
// zh

DIDEVCAPS				dcJoystick;

DIDEVCAPS				dcJoystick2;

IDirectInput8			*mDInput;
//IDirectInputDevice8		*mKeyboard;
char					mKeyboardState[256];

int Count = 0;

DInput* gDInput = 0;

DInput::DInput(DWORD joystickCoopFlags)
{
	//clear the memory
	ZeroMemory(&js, sizeof(js));
	ZeroMemory(&js2, sizeof(js2));

	//create Direct Input Object
	HR(DirectInput8Create(gd3dApp->getAppInstance(), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&mDInput, 0));

	//Create Direct Input Devices, then set parameters and acquire
	HR(mDInput->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback, NULL, DIEDFL_ATTACHEDONLY));

	if(mJoystick[0] == NULL)
		MessageBox(gd3dApp->getMainWindowHandle(), "No Joystick 1 Found", "Error", 0);

	if(mJoystick[1] == NULL)
		MessageBox(gd3dApp->getMainWindowHandle(), "No Joystick 2 Found", "Error", 0);

	HR(mJoystick[0]->SetDataFormat(&c_dfDIJoystick2));
	HR(mJoystick[1]->SetDataFormat(&c_dfDIJoystick2));
	HR(mJoystick[0]->SetCooperativeLevel(gd3dApp->getMainWindowHandle(), joystickCoopFlags));
	HR(mJoystick[1]->SetCooperativeLevel(gd3dApp->getMainWindowHandle(), joystickCoopFlags));
	dcJoystick.dwSize = sizeof(DIDEVCAPS);

	HR(mJoystick[0]->GetCapabilities(&dcJoystick));

	dcJoystick2.dwSize = sizeof(DIDEVCAPS);
	HR(mJoystick[1]->GetCapabilities(&dcJoystick2));

	HR(mJoystick[0]->Acquire());
	HR(mJoystick[1]->Acquire());

}

BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE *pdidInstance, VOID* pContext)
{


	HRESULT hr;

    // Obtain an interface to the enumerated joystick.
	hr = mDInput->CreateDevice(pdidInstance->guidInstance, &mJoystick[Count], NULL);
	if(FAILED(hr)) 
		return DIENUM_CONTINUE;

	else
	{
		Count++;
		if (Count >= 2)
		{
			return DIENUM_STOP;
		}
	}

    return DIENUM_CONTINUE;
}

void DInput::pollJoystick()
{
	HRESULT hr;
	HRESULT hr2;
	hr = mJoystick[0]->Poll();
	hr2 = mJoystick[1]->Poll();


	if(FAILED(hr))
	{
		//joystick lost, zero our data structure
		ZeroMemory(&js, sizeof(js));

		//try and acquire for next poll
		mJoystick[0]->Poll();

	}
	if(FAILED(hr2))
	{
		//joystick lost, zero our data structure
		ZeroMemory(&js2, sizeof(js2));

		//try and acquire for next poll
		mJoystick[1]->Poll();

	}
}

DInput::~DInput()
{
	//release Direct Input Object
	ReleaseCOM(mDInput);
	
	//unacquire devices, give them back to the system!!!
	mJoystick[0]->Unacquire();
	mJoystick[1]->Unacquire();

	//release the devices
	ReleaseCOM(mJoystick[0]);
	ReleaseCOM(mJoystick[1]);
}
